<template>
    <div class="register-container">
        <div class="register-box">
            <h2>用户注册</h2>
            <el-form ref="registerFormRef" :model="formData" :rules="rules" label-position="top">
                <el-form-item label="选择学校" prop="school">
                    <el-select 
                        v-model="formData.school" 
                        placeholder="请选择学校" 
                        filterable
                        class="full-width"
                    >
                        <el-option
                            v-for="item in schoolOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formData.username" placeholder="请输入用户名" :prefix-icon="User" />
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                        show-password />
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码"
                        :prefix-icon="Lock" show-password />
                </el-form-item>

                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入手机号码" :prefix-icon="Phone" />
                </el-form-item>

                <el-form-item label="验证码" prop="code">
                    <div class="code-input">
                        <el-input v-model="formData.code" placeholder="请输入验证码" :prefix-icon="Key" />
                        <el-button type="primary" :disabled="countdown > 0" @click="handleSendCode">
                            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                        </el-button>
                    </div>
                </el-form-item>

                <el-button type="primary" :loading="loading" class="submit-btn" @click="handleRegister">
                    注册
                </el-button>

                <div class="login-link">
                    已有账号？
                    <el-link type="primary" @click="$router.push('/login')">立即登录</el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Key } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { register, sendVerificationCode } from '../api/user'
import { getSchools, type School } from '../api/school'

const router = useRouter()
const registerFormRef = ref<FormInstance>()
const loading = ref(false)
const countdown = ref(0)

const formData = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    code: '',
    school: ''
})

// 学校选项，初始为空数组，将通过API加载
const schoolOptions = ref<{ value: string | number, label: string }[]>([])
const schoolsLoading = ref(false)

// 在组件挂载时获取学校列表
onMounted(async () => {
    await loadSchools()
})

// 加载学校列表的方法
const loadSchools = async () => {
    try {
        schoolsLoading.value = true
        const res = await getSchools()
        if (res.code === 200 && res.data) {
            // 将后端返回的学校数据转换为选择器需要的格式
            schoolOptions.value = res.data.map((school: School) => ({
                value: school.id,
                label: school.name
            }))
        } else {
            ElMessage.warning('获取学校列表失败')
        }
    } catch (error) {
        console.error('获取学校列表出错:', error)
        ElMessage.error('获取学校数据失败，请刷新页面重试')
    } finally {
        schoolsLoading.value = false
    }
}

const validatePass = (rule: any, value: string, callback: Function) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (value.length < 6) {
        callback(new Error('密码长度不能小于6个字符'))
    } else {
        if (formData.confirmPassword !== '') {
            registerFormRef.value?.validateField('confirmPassword')
        }
        callback()
    }
}

const validatePass2 = (rule: any, value: string, callback: Function) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, message: '用户名长度不能小于3个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, validator: validatePass, trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
    ],
    school: [
        { required: true, message: '请选择学校', trigger: 'change' }
    ]
}

const handleSendCode = async () => {
    if (!formData.phone) {
        ElMessage.warning('请输入手机号码')
        return
    }

    try {
        // 调用发送验证码API
        const res = await sendVerificationCode(formData.phone, 'register')
        if (res.code === 200) {
            // 验证码发送成功，开始倒计时
            countdown.value = 60
            const timer = setInterval(() => {
                countdown.value--
                if (countdown.value <= 0) {
                    clearInterval(timer)
                }
            }, 1000)
            ElMessage({
                message: '验证码已发送',
                type: 'success',
                duration: 4000,
                showClose: true
            })
        }
    } catch (error) {
        console.error('发送验证码出错:', error)
    }
}

const handleRegister = async () => {
    if (!registerFormRef.value) return

    try {
        await registerFormRef.value.validate()
        loading.value = true

        // 调用注册API
        const res = await register({
            username: formData.username,
            password: formData.password,
            phone: formData.phone,
            code: formData.code,
            school: formData.school
        })

        if (res.code === 200) {
            // 注册成功后可以将学校信息保存，以便登录时使用
            localStorage.setItem('lastSchool', formData.school.toString())
            
            ElMessage({
                message: '注册成功',
                type: 'success',
                duration: 4000,
                showClose: true
            })
            router.push('/login')
        }
    } catch (error) {
        console.error('注册验证失败:', error)
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.register-container {
    min-height: calc(100vh - 180px);
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
}

.register-box {
    width: 100%;
    max-width: 400px;
    padding: 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
}

.code-input {
    display: flex;
    gap: 10px;
}

.code-input .el-input {
    flex: 1;
}

.submit-btn {
    width: 100%;
    margin-bottom: 20px;
}

.login-link {
    text-align: center;
    color: #606266;
}

.full-width {
    width: 100%;
}
</style>